﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using ThridGroup.ERP.ProductionSystem;
using ThridGroup.ERP.Application.Contracts.ProductionSystem;
using ThridGroup.ERP.Application.Contracts.DTO;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Dtos;
using Volo.Abp.ObjectMapping;
using Volo.Abp;

namespace ThridGroup.ERP.ProductionSystem
{
    /// <summary>
    /// 点检保养项目服务实现    ---tsh
    /// </summary>
    public class MaintenanceplanServcices : ApplicationService, IMaintenanceplanServcices
    {
        private readonly IRepository<MaintenanceplanModel, int> _maintenanceplanRepository;
        private readonly ILogger<MaintenanceplanServcices> _logger;

        public MaintenanceplanServcices(IRepository<MaintenanceplanModel, int> maintenanceplanRepository, ILogger<MaintenanceplanServcices> logger)
        {
            _maintenanceplanRepository = maintenanceplanRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="input">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResultDto<MaintenanceplanDto>> GetListAsync(QueryMaintenanceplanDto input)
        {
            try
            {
                var queryable = await _maintenanceplanRepository.GetQueryableAsync();

                // 添加查询条件
                if (!string.IsNullOrWhiteSpace(input.ProjectCode))
                {
                    queryable = queryable.Where(x => x.ProjectCode.Contains(input.ProjectCode));
                }

                if (!string.IsNullOrWhiteSpace(input.ProjectName))
                {
                    queryable = queryable.Where(x => x.ProjectName.Contains(input.ProjectName));
                }

                if (!string.IsNullOrWhiteSpace(input.ProjectType))
                {
                    queryable = queryable.Where(x => x.ProjectType == input.ProjectType);
                }

                if (!string.IsNullOrWhiteSpace(input.WhethertoEnable))
                {
                    queryable = queryable.Where(x => x.WhethertoEnable == input.WhethertoEnable);
                }

                // 根据项目编码排序
                queryable = queryable.OrderBy(x => x.ProjectCode);

                // 分页
                var totalCount = await queryable.CountAsync();
                var entities = await queryable
                    .Skip(input.SkipCount)
                    .Take(input.MaxResultCount)
                    .ToListAsync();

                var dtos = ObjectMapper.Map<List<MaintenanceplanModel>, List<MaintenanceplanDto>>(entities);

                return new PagedResultDto<MaintenanceplanDto>(totalCount, dtos);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取点检保养计划列表失败");
                throw new UserFriendlyException("获取点检保养计划列表失败");
            }
        }

        /// <summary>
        /// 根据ID获取详情
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns>详情信息</returns>
        public async Task<MaintenanceplanDto> GetAsync(int id)
        {
            try
            {
                var entity = await _maintenanceplanRepository.GetAsync(id);
                return ObjectMapper.Map<MaintenanceplanModel, MaintenanceplanDto>(entity);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取点检保养计划详情失败，ID: {id}");
                throw new UserFriendlyException("获取点检保养计划详情失败");
            }
        }

        /// <summary>
        /// 创建新项目
        /// </summary>
        /// <param name="input">创建数据</param>
        /// <returns>创建结果</returns>
        public async Task<MaintenanceplanDto> CreateAsync(CreateUpdateMaintenanceplanDto input)
        {
            try
            {
                // 如果启用自动生成编码
                if (input.AutoGenerateCode)
                {
                    input.ProjectCode = await GenerateProjectCodeAsync(input.ProjectType);
                }
                else
                {
                    // 检查编码是否已存在
                    if (await IsProjectCodeExistAsync(input.ProjectCode))
                    {
                        throw new Exception($"项目编码 {input.ProjectCode} 已存在");
                    }
                }

                var entity = new MaintenanceplanModel
                {
                    ProjectCode = input.ProjectCode,
                    ProjectName = input.ProjectName,
                    ProjectType = input.ProjectType,
                    ProjectContent = input.ProjectContent,
                    //CreateUser = CurrentUser?.UserName ?? "System"
                };

                var createdEntity = await _maintenanceplanRepository.InsertAsync(entity, true);
                return ObjectMapper.Map<MaintenanceplanModel, MaintenanceplanDto>(createdEntity);
            }
            catch (Exception ex)
            {
                throw new Exception($"创建点检保养项目失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新项目
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="input">更新数据</param>
        /// <returns>更新结果</returns>
        public async Task<MaintenanceplanDto> UpdateAsync(int id, CreateUpdateMaintenanceplanDto input)
        {
            try
            {
                var entity = await _maintenanceplanRepository.GetAsync(id);

                // 如果项目编码有变化，检查新编码是否已存在
                if (entity.ProjectCode != input.ProjectCode)
                {
                    if (await IsProjectCodeExistAsync(input.ProjectCode, id))
                    {
                        throw new Exception($"项目编码 {input.ProjectCode} 已存在");
                    }
                }

                //更新实体
        entity.ProjectCode = input.ProjectCode;
                entity.ProjectName = input.ProjectName;
                entity.ProjectType = input.ProjectType;
                entity.ProjectContent = input.ProjectContent;
                entity.Standard = input.Standard ?? "";
                //entity.UpdateUser = CurrentUser?.UserName ?? "System";

                var updatedEntity = await _maintenanceplanRepository.UpdateAsync(entity, true);
                return ObjectMapper.Map<MaintenanceplanModel, MaintenanceplanDto>(updatedEntity);
            }
            catch (Exception ex)
            {
                throw new Exception($"更新点检保养项目失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns>删除结果</returns>
        public async Task DeleteAsync(int id)
        {
            try
            {
                await _maintenanceplanRepository.DeleteAsync(id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除点检保养计划失败，ID: {id}");
                throw new UserFriendlyException("删除点检保养计划失败");
            }
        }

        /// <summary>
        /// 批量删除项目
        /// </summary>
        /// <param name="ids">主键ID列表</param>
        /// <returns>删除结果</returns>
        public async Task DeleteBatchAsync(List<int> ids)
        {
            try
            {
                await _maintenanceplanRepository.DeleteManyAsync(ids);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除点检保养计划失败");
                throw new UserFriendlyException("批量删除点检保养计划失败");
            }
        }

        /// <summary>
        /// 生成项目编码
        /// </summary>
        /// <param name="projectType">项目类型</param>
        /// <returns>新的项目编码</returns>
        public async Task<string> GenerateProjectCodeAsync(string projectType)
        {
            try
            {
                string prefix;
                if (projectType == "设备点检计划" || projectType == "设备点检")
                {
                    prefix = "SUB"; // SUB=设备点检
                }
                else if (projectType == "设备保养计划" || projectType == "设备保养")
                {
                    prefix = "SUM"; // SUM=设备保养
                }
                else if (projectType == "综合维护计划")
                {
                    prefix = "COM"; // COM=综合维护
                }
                else
                {
                    prefix = "GEN"; // GEN=通用
                }
                
                string dateStr = DateTime.Now.ToString("yyyyMMdd");

                var queryable = await _maintenanceplanRepository.GetQueryableAsync();
                var todayCount = await queryable
                    .Where(x => x.ProjectCode.StartsWith(prefix))
                    .CountAsync();

                string sequence = (todayCount + 1).ToString("D3");
                return $"{prefix}{dateStr}{sequence}";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成项目编码失败");
                throw new UserFriendlyException("生成项目编码失败");
            }
        }

        /// <summary>
        /// 检查项目编码是否存在
        /// </summary>
        /// <param name="projectCode">项目编码</param>
        /// <param name="excludeId">排除的ID（用于修改时检查）</param>
        /// <returns>是否存在</returns>
        public async Task<bool> IsProjectCodeExistAsync(string projectCode, int? excludeId = null)
        {
            try
            {
                var queryable = await _maintenanceplanRepository.GetQueryableAsync();
                queryable = queryable.Where(x => x.ProjectCode == projectCode);

                if (excludeId.HasValue)
                {
                    queryable = queryable.Where(x => x.Id != excludeId.Value);
                }

                return await queryable.AnyAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查项目编码是否存在失败");
                throw new UserFriendlyException("检查项目编码是否存在失败");
            }
        }

        /// <summary>
        /// 获取所有项目类型
        /// </summary>
        /// <returns>项目类型列表</returns>
        public async Task<List<string>> GetProjectTypesAsync()
        {
            try
            {
                return await Task.FromResult(new List<string> { "设备点检计划", "设备保养计划", "综合维护计划" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取项目类型列表失败");
                throw new UserFriendlyException("获取项目类型列表失败");
            }
        }

        /// <summary>
        /// 获取所有点检保养计划（不分页）
        /// </summary>
        public async Task<List<MaintenanceplanDto>> GetAllAsync()
        {
            try
            {
                var entities = await _maintenanceplanRepository.GetListAsync();
                return ObjectMapper.Map<List<MaintenanceplanModel>, List<MaintenanceplanDto>>(entities);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有点检保养计划失败");
                throw new UserFriendlyException("获取所有点检保养计划失败");
            }
        }
    }
}
